package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.UserService;
import com.heima.user.utils.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements UserService {
    @Override
    public ResponseResult<?> login(LoginDto loginDto) {
        if (!StringUtils.isEmpty(loginDto.getPassword())&&!StringUtils.isEmpty(loginDto.getPhone())) {
            ApUser apUser = baseMapper.selectOne(new QueryWrapper<ApUser>().lambda().eq(ApUser::getPhone, loginDto.getPhone()));
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户不存在");
            }
            String password = loginDto.getPassword();
            String salt = apUser.getSalt();
            String webPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if(!apUser.getPassword().equals(webPassword)){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map map = new HashMap<>();
            map.put("token", token);
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        }else {
            String token = AppJwtUtil.getToken(0L);

            return ResponseResult.okResult(token);
        }
    }
}
